import {
  ref, reactive, toRefs, computed, onBeforeMount
} from 'vue';
import type { Ref, SetupContext } from 'vue';

export interface TableItem {
  label: string,
  prop: string,
  width?: number,
  minWidth?: number,
  fixed?: Boolean | 'left' | 'right',
  sortable?: Boolean | 'custom',
  sortMethod?: (a: any, b: any) => number,
  sortBy?: string,
  showOverflowTooltips?: Boolean,
  iconClass?: string,
  [key: string]: any
}

export interface TableConfig {
  showIndex?: Boolean,
  showSelection?: Boolean,
  isFrontPaging?: Boolean,
  header: TableItem[],
  getDataList: (s: number, n: number) => Promise<ResType>
}

interface TableProps {
  id: string,
  config: TableConfig,
  showPagination: Boolean
}

export function useTable(props: TableProps, ctx: SetupContext<any>) {
  const { getDataList, isFrontPaging } = props.config;

  const header = computed(() => props.config.header || []);

  const list: Ref<any[]> = ref([]);

  const allList: Ref<any[]> = ref([]); // 前端分页储存所有数据

  const page = reactive({
    size: 10, number: 1, total: 0
  });

  const rowKey = (row: AnyObject): string => {
    return row[props.id];
  };

  const refleshTable = async () => { // 刷新
    page.number = 1;
    const { size, number } = page;
    const { data, total } = await getDataList(size, number);

    if (isFrontPaging) {
      allList.value = data;
      onPage(size, number);
    } else {
      list.value = data;
    }

    page.total = total || data.length;
  };

  const setSize = (size: number) => {
    page.size = size;
    onPage(page.size, page.number);
  };

  const setNumber = (number: number) => { //
    page.number = number;
    onPage(page.size, page.number);
  };

  const onSelect = (selection: any[]) => {
    ctx.emit('selectChange', selection);
  };

  const onPage = async (size: number, number: number) => { // 翻页方法
    if (isFrontPaging) {
      list.value = allList.value.splice(size * (number - 1), size);
    } else {
      const { data, total } = await getDataList(size, number);

      list.value = data;
      page.total = total || data.length;
    }
  };

  onBeforeMount(async () => {
    refleshTable();
  });

  return {
    list,
    header,
    rowKey,
    ...toRefs(page),
    refleshTable,
    setSize,
    setNumber,
    onSelect
  };
}
